package com.leyou.auth.config;

import com.leyou.common.auth.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @package com.leyou.auth.config
 * @description: 读取公钥私钥的配置类
 * @author: 许超越
 * @date 2019/7/7 16:34
 * @version: V1.0
 */
@Data
@Slf4j
@ConfigurationProperties(prefix = "ly.jwt")
public class JwtProperties implements InitializingBean {
    /**
     * 公钥地址
     */
    private String pubKeyPath;
    /**
     * 私钥地址
     */
    private String priKeyPath;

    private PublicKey publicKey;

    private PrivateKey privateKey;

    private UserTokenProperties userTokenProperties = new UserTokenProperties();

    private AppTokenProperties appTokenProperties = new AppTokenProperties();

    @Data
    public class UserTokenProperties{
        /**
         * token过期时长
         */
        private int expire;
        /**
         * 存放token的cookie名称
         */
        private String cookieName;
        /**
         * 存放token的cookie的domain
         */
        private String cookieDomain;
        /**
         * 最大的刷新剩余时间
         */
        private Long maxRefreshInterval;
    }

    @Data
    public class AppTokenProperties{
        /**
         * 微服务token过期时长
         */
        private int expire;
        /**
         * 服务id
         */
        private Long id;
        /**
         * 服务密码
         */
        private String secret;
        /**
         * 携带token的请求头的名称
         */
        private String headerName;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            //获取公钥
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            //获取私钥
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            log.error("读取公钥和私钥失败，原因：{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
